package com.mbt.bluetooth.manager;

import java.io.IOException;
import java.io.InputStream;

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

/**
* A class that demonstrates Bluetooth communication between server mode PC and
* client mode device through serial port profile.
*
*/
public class BluetoothConnectionManager {

	// serial port profile
    /** The UUID. */
	protected String UUID = new UUID("1101", true).toString();
    
    /** The discovery mode. */
    protected int discoveryMode = DiscoveryAgent.GIAC; // no paring needed

    /** The in. */
    private static InputStream in;
    
    
    public static boolean isConnected() {
		return isConnected;
	}

	public static void setConnected(boolean isConnected) {
		BluetoothConnectionManager.isConnected = isConnected;
	}

	private static boolean isConnected = false;
    
    /** The notifier. */
    StreamConnectionNotifier notifier = null;
    StreamConnection streamConnection = null;
    /*-
     *
     * ---- Connection handling attributes ----
     */
    /** The end token. */
    protected int endToken = 255;
    
    /** The bluetooth connection manager. */
    private static BluetoothConnectionManager bluetoothConnectionManager = new BluetoothConnectionManager();
    
    public StreamConnection getStreamConnection() {
		return streamConnection;
	}

	public void setStreamConnection(StreamConnection streamConnection) {
		this.streamConnection = streamConnection;
	}

	/**
     * Instantiates a new bluetooth connection manager.
     */
    private BluetoothConnectionManager() {
        try {
            LocalDevice device = LocalDevice.getLocalDevice();
            device.setDiscoverable(DiscoveryAgent.GIAC);

            String url = "btspp://localhost:" + UUID + ";name=PCServerCOMM";

            log("Create server by uri: " + url);
            notifier = (StreamConnectionNotifier) Connector.open(url);
            log("Created. Waiting to accept and open ");
            streamConnection = notifier.acceptAndOpen();
            log("Accept and open ");
            isConnected = true;
        } catch (Throwable e) {
            log(e);
        }
    }
    
    /**
     * Accept.
     *
     * @return the bluetooth connection manager
     */
    public static BluetoothConnectionManager accept(){
    	return bluetoothConnectionManager;
    }

     
    /**
     * Log.
     *
     * @param msg the msg
     */
    private void log(String msg) {

       System.out.println("LOG : "+msg);
    }

    /**
     * Log.
     *
     * @param e the e
     */
    private void log(Throwable e) {
        log(e.getMessage());
        e.printStackTrace();
    }
    
    /**
     * Recieve messages.
     *
     * @return the string
     */
    public String  recieveMessages()
    {
        byte[] data = null;   
        try 
        {  if(in == null)
        	in = streamConnection.openDataInputStream();
           int length = in.read();       
           if(length <= 0){
        	   return null;
           }
           data= new byte[length];
           length = 0;
       
           while (length != data.length) 
           {     
                   int ch = in.read(data, length, data.length - length);

                   if (ch == -1)
                   {
                     throw new IOException("Can't read data");
                   }
                   length += ch;
           }      

           
        }
        catch (IOException e) 
        {
              System.err.println(e);
        } 
        
        return data != null? new String(data) : null;
    }
    
    /*-
     *   -------  Bootstrap section, i.e., main method -------
     */
}